﻿var NoteApp = Backbone.Router.extend({

    routes: {
        "": "list",
        "notes": "list",
        "notes/new": "newNote",
        "notes/add": "addNote",
        "notes/del/:id": "delNote",
        "notes/addimage": "addCameraImage",
        "notes/weibo": "weibo",
        "notes/settings": "showSettings",
        "notes/backup": "backup",
        "notes/restore": "restore",
        "notes/:id": "showNote"
    },
    
    initialize: function () {
        // 将所有CSS样式为.back的DOM元素添加浏览器的页面返回动作
    	var self = this;
        $('.back').live('click', function(event) {
            window.history.back();
            self.stopWatch();
            return false;
        });
        this.firstPage = true;
        this.noteList = new NoteList();
        // 示例数据
        this.noteList.add(new Note({id: 1, content: "到了机场记得打印行程单", date: Date.parse("2012-5-17")}));
        this.noteList.add(new Note({id: 3, content: "本周末要恢复健身", date: Date.parse("2012-5-19")}));
        this.noteList.add(new Note({id: 2, content: "不要忘记带伞", date: Date.parse("2012-5-18")}));
        this.watchID = null;
        this.isConfirm = false;
	    this.oldValue = {x: null,y: null,z: null};
        this.backupServer = "http://www.tallshorter.com";
    },

    // 应用的首页面，展示笔记列表
    list: function() {
        var db = getDB();
        var self = this;
        createNoteTable(db, function() {
            getNotes(db, function(noteList) {
                self.changePage(new NoteListPage({model: noteList}));
                $('#noteListView li').swipeDelete({
            		btnTheme: 'e',
            		btnLabel: '删除',
            		btnClass: 'aSwipeButton',
            		click: function(e){
            			e.preventDefault();
            			var url = $(this).parents('li').attr('data-swipeurl');
            			$(this).parents('li').slideUp();
            			self.navigate(url, {trigger: true});
            		}
            	});
            });
        });
    },

    // 新建笔记页面
    newNote: function() {
        this.changePage(new NewNoteView({model: new Note()}));
    },

    // 添加笔记操作
    addNote: function() {       
       //alert("addNote id:"+$("#hiddenId").attr("value"));  
        var newNote ;
    	var self = this;
    	var idValue = $("#hiddenId").attr("value");
    	var categoryVal = $(":radio:checked").val();
    	if (idValue == "" || idValue== undefined)
    	{
    	   categoryVal = "category-blue";
    	}
    	if (idValue == "" || idValue== undefined)
    	{
    		newNote = new Note({content: $("#newNoteContent").val(),imageContent:$("#photoimg").attr("src"),category:categoryVal});
    		insertNote(getDB(), newNote, function() {
            	self.navigate("", {trigger: true});
            	self.stopWatch();
        	});
    	}
    	else 
    	{
    		newNote = new Note({content: $("#newNoteContent").val(),imageContent:$("#photoimg").attr("src"),id: idValue,category:categoryVal});
    		updateNote(getDB(), newNote, function() {
            	self.navigate("", {trigger: true});
            	self.stopWatch();
        	});
    	}
    },

    // 显示笔记页面
    showNote: function(id) {
        var self = this;
        getNoteById(getDB(), id, function(note) {
            self.startWatch();
            self.changePage(new NewNoteView({model: note}));
            //获得category信息
            var categoryVal = note.get("category");
            //alert(note.get("imageContent"));
            //alert(categoryVal);
            if(categoryVal =="default" || categoryVal == "category-blue"){
                 $("#category-blue").attr("checked",true).checkboxradio("refresh");
            } else if (categoryVal=="category-green"){
                $("#category-green").attr("checked",true).checkboxradio("refresh");
            }else if (categoryVal=="category-pink"){
                $("#category-pink").attr("checked",true).checkboxradio("refresh");
            }else if (categoryVal=="category-purple"){
                $("#category-purple").attr("checked",true).checkboxradio("refresh");
            }else if (categoryVal=="category-red"){
                $("#category-red").attr("checked",true).checkboxradio("refresh");
            }else if (categoryVal=="category-yellow"){
                $("#category-yellow").attr("checked",true).checkboxradio("refresh");
            }
            /*var noteContent = $("#newNoteContent").attr("value");
            WB2.anyWhere(function(W){
                W.widget.publish({
                    id : 'publish', default_text : noteContent
                });
            });*/
        });

    },
    
    // 删除某条笔记
    delNote: function(id) {
        var self = this;
        deleteNoteById(getDB(), id, function(){
        	self.navigate("", {trigger: true});
        });
    },
    
    addCameraImage: function() {
        navigator.camera.getPicture(getPictureSuccess, getPictureFail, 
            {
                quality: 100,
                destinationType: Camera.DestinationType.DATA_URL,
                sourceType: navigator.camera.PictureSourceType.CAMERA,
                targetHeight: 200,
                targetWidth: 150
            });
        function getPictureSuccess(imageData){
            $("#photoimg").remove();
            $("#newNoteContentDiv").append("<img id='photoimg' width=150 height=200 src='data:image/jpeg;base64," + imageData + "' />");
        }
        function getPictureFail(message) {
            alert("操作失败 请重试，错误原因 " + message);
        }
    },
    
    weibo: function() {
    	var self = this;
    	var noteContent = $("#newNoteContent").attr("value");
    	if(!WB2.checkLogin()){
        	WB2.login(function(){
        		self.sendWeibo(noteContent);
        	});
        }else{
        	self.sendWeibo(noteContent);
        }
    },


    sendWeibo: function(note) {
    	WB2.anyWhere(function(W){
    	W.parseCMD("/statuses/update.json", function(sResult, bStatus){
    		console.log(sResult.error);
    		console.log(sResult.request);
    	    if(bStatus == true) {
    	    	navigator.notification.alert("发送成功");
    	    }else{
    	    	navigator.notification.alert("发送失败："+sResult.error);
    	    }
    	},{
    		source:'419306123', status : note
    	},{
    	    method: 'post'
    	});
    	});
    },
    
    showSettings: function() {
        this.changePage(new SettingsView());
    },

    backup: function() {
        var self = this;
        getNotes(getDB(), function(noteList) {
            $.post(self.backupServer + '/backup.php', {noteList: noteList.toJSONString()},
                function() {
                    alert("备份成功");
                    self.navigate("notes/settings", {trigger: true});
                }
            ).error(function() { 
                alert("操作失败，请重试"); 
            });
        });
    },

    restore: function() {
        var self = this;
        $.get(this.backupServer + '/restore.php', function(data) {
            var noteList = new NoteList();
            noteList.loadFromJSONString(data);
            var db = getDB();
            cleanDB(db, function() {
                restoreDB(db, noteList);
                self.navigate("notes", {trigger: true});
            });
        });
    },
    
    startWatch: function() {
        var options = { frequency: 300 };
        var self = this;
        this.watchID = navigator.accelerometer.watchAcceleration(function(newValue) {
    	    var changes = {};
    		bound = 3;
    		if (self.oldValue!=null&&self.oldValue!== undefined) {
	    		changes.x = Math.abs(self.oldValue.x, newValue.x);
	    		changes.y = Math.abs(self.oldValue.y, newValue.y);
	    		changes.z = Math.abs(self.oldValue.z, newValue.z);
    		}
    		if (changes.x > bound && changes.y > bound && changes.z > bound) {
    			console.log('检测到手机晃动');
    			if(!this.isConfirm){
    				this.isConfirm = true;
    				self.comfirmDelete();
    			}
    		}
    		self.oldValue = {x: newValue.x,y: newValue.y,z: newValue.z};
        }, function() {
            alert('onError!');
        }, options);
        console.log("this.watchID"+this.watchID);
    },

    stopWatch: function() {
        if (this.watchID!=undefined&&this.watchID!=null) {
            navigator.accelerometer.clearWatch(this.watchID);
            this.watchID = null;
        }
    },
    
    comfirmDelete: function() {
    	var self = this;
		navigator.notification.confirm("确认删除吗？", function(buttonIndex) {
		    if (buttonIndex == 1) { // 确认
		    	var idValue = $("#hiddenId").attr("value");
		    	self.delNote(idValue);
		    } else { // 取消
		    	console.log("cancelled");
		    }
	    	self.isConfirm = false;
		}, "提示", "确认,取消");
    },
    
    // 页面切换
    changePage: function (page) {
        $(page.el).attr('data-role', 'page'); // 修饰为jQuery Mobile中的page
        page.render();
        $('body').append($(page.el));
        var transition = $.mobile.defaultPageTransition;
        if (this.firstPage) { // 首个页面不需要页面切换效果
            transition = 'none';
            this.firstPage = false;
        }
        // 切换并渲染页面
        $.mobile.changePage($(page.el), {changeHash: false, transition: transition});
    },

    // 启动应用，进行页面的路由
    start: function() {
        Backbone.history.start();
    }
    
});

$(document).ready(function() {
    document.addEventListener("deviceready", function() {
        console.log("******deviceready******");
    }, false);
    // 装载应用所需的视图模板
    tpl.loadTemplates(["note-details", "note-list-item", "notes-page", "new-note", "settings"], function() {
        // 视图模板装载完毕，创建MiniNote应用实例并启动它
        app = new NoteApp();
        app.start();
    });
   
});